package service.protobuf;

import bean.DemoProtocol;
import bean.GatewayProtobufProtocol;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import org.apache.log4j.Logger;


/**
 * Created by momochen on 2017-07-18.
 */
public class NettyProtobufTCPServiceHandler extends SimpleChannelInboundHandler<GatewayProtobufProtocol.ProtobufProtocol> {
    private static Logger logger = Logger.getLogger(NettyProtobufTCPServiceHandler.class);

    static volatile SocketChannel channelService;

    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GatewayProtobufProtocol.ProtobufProtocol msg) throws Exception {
        if (msg == null) {
            return;
        }

//        GatewayProtobufProtocol.ProtobufProtocol protocol = (GatewayProtobufProtocol.ProtobufProtocol) msg;
//        System.out.println("==>"+protocol.getLenght());

        System.out.println("==>" + msg.getLenght());
        for (int i = 0; i < msg.getDatas(0).size(); i++) {
            System.out.print(byteTo16(msg.getDatas(0).byteAt(i)));
        }
        System.out.println();

        ChannelFuture future = channelHandlerContext.writeAndFlush(msg);
//        future.addListener(future1 -> System.out.println("==>" + future.isSuccess()));

        ReferenceCountUtil.release(msg);
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
            throws Exception {
        String socketString = ctx.channel().remoteAddress().toString();

        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
//                System.out.println("===>READER_IDLE");
                ctx.disconnect();
            } else if (event.state() == IdleState.WRITER_IDLE) {
//                System.out.println("===>WRITER_IDLE");
                ctx.disconnect();
            } else if (event.state() == IdleState.ALL_IDLE) {
//                System.out.println("===>ALL_IDLE");
                ctx.disconnect();
            }
        }
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
//        channel = (SocketChannel) ctx.channel();
//        System.out.println("===>handlerAdded");
    }

    //客户端关闭
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        // 移除
        ctx.close();
//        System.out.println("===>channelInactive");
    }

    //异常消息
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
//        ctx.close();
        cause.printStackTrace();
//        System.out.println("===>exceptionCaught");
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
//        ctx.close();
//        System.out.println("===>channelReadComplete");
    }

    public static String byteTo16(byte bt) {
        String[] strHex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
        String resStr = "";
        int low = (bt & 15);
        int high = bt >> 4 & 15;
        resStr = strHex[high] + strHex[low];
        return resStr;
    }
}
